package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// CORS 中间件处理跨域资源共享
func CORS() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 记录请求信息
		fmt.Printf("Request Method: %s, Origin: %s\n", c.Request.Method, c.Request.Header.Get("Origin"))

		// 动态获取并验证请求源
origin := c.Request.Header.Get("Origin")
// 允许前端开发服务器地址
if origin == "http://localhost:8080" || origin == "http://localhost:8081" {
    c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
}
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With, X-User-ID, X-Token")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, HEAD, PATCH, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			fmt.Println("Handling OPTIONS request")
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}
